import { type PaginationProps } from "@pureadmin/table";
import { priceToThousands, addZero } from "@pureadmin/utils";
import { ref, computed, reactive, onMounted, nextTick } from "vue";
import {
  SecuritiesFundDividendFundRedemption,
  SecuritiesFundDividendTaxPlanningAnalysis,
  SecuritiesFundDividendGetAllFundDividend,
  SecuritiesFundDividendGetMyFundDividend,
  SecuritiesFundDividendPurchasedFundDividend,
  SecuritiesFundDividendGetMyFundDividendByCode,
  SecuritiesFundDividendGetTaxPlanningAnalysisData
} from "@/api/stu/Cecurity";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import qs from "qs";
export function useTaxPlanning() {
  const pattern = /^[0-9]\d*$/;
  const route = useRoute();
  const btnloading = ref<boolean>(false)
  const loading = ref<boolean>(true)
  const dataList = ref();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const loadings = ref<boolean>(true)
  const dataLists = ref();
  const paginations = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const DialogVisible = ref(false);
  const DialogState = ref<Number>(0);
  const DateVisible = ref(false);//日期窗口
  const DateValue = ref("");//
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    }, {
      label: "基金代码",
      prop: "fundCode"
    }, {
      label: "基金名称",
      prop: "fundName",
    }, {
      label: "权益登记日",
      prop: "registrationTime"
    }, {
      label: "除息日期",
      prop: "exdividendTime"
    }, {
      label: "分红（元/份）",
      prop: "dividend"
    }, {
      label: "分红发放日",
      prop: "dividendSendTime"
    }, {
      label: "累积分红次数",
      prop: "totalDividendNum"
    }, {
      label: "操作",
      fixed: "right",
      width: 100,
      slot: "operation"
    }
  ];
  const resultNav = ref("")
  const FormConten = ref<any>({});
  // 购买
  async function Buy(row, nums) {
    DialogState.value = nums;
    if (nums == 1) {
      // 购买基金需要选择日期进行计算单位净值
      DateVisible.value = true;
      FormConten.value = row;
    } else if (nums == 2) {
      // TODO:基金分红
      const data = qs.stringify({
        fundCode: row.fundCode,
        "planId": route.query.planId,
        "taskId": route.query.taskId
      });
      const res = await SecuritiesFundDividendGetMyFundDividendByCode(data);
      if (res.success) {
        ElMessage.success(res.msg)
        FormConten.value = res.data;
        DialogVisible.value = true;
        GetDataLists()
      } else {
        ElMessage.error(res.msg)
      }
    } else if (nums == 3) {
      // 基金赎回需要选择日期进行计算单位净值

      FormConten.value = row;
      DateVisible.value = true;
    } else if (nums == 4) {
      const data = qs.stringify({
        purchasedId: row.purchasedId,
        "planId": route.query.planId,
        "taskId": route.query.taskId
      });
      const res = await SecuritiesFundDividendGetTaxPlanningAnalysisData(data);
      if (res.success) {
        ElMessage.success(res.msg)
        FormConten.value = { ...row, ...res.data };
        console.log("123", FormConten.value)
        DialogVisible.value = true;
        GetDataLists()
      } else {
        ElMessage.error(res.msg)
      }
    }
  };

  // 取消选择时间
  function close_date() {
    DateVisible.value = false;
    DateValue.value = ""
  }
  // 确定选择时间 -- 计算净值
  function sure_date() {
    if (DateValue.value == '' || DateValue.value == null || !DateValue.value) {
      ElMessage.warning("请选择日期")
      return
    }
    DateVisible.value = false;
    nextTick(() => {
      DialogVisible.value = true;
    })
    // 计算单位费率

    let freezeTime = '2023-09-06'
    let day = new Date(DateValue.value).getTime() - new Date(freezeTime).getTime();//日期转时间戳
    let dayCount = Math.floor(day / 86400000);//时间戳获取天数
    // 申购日期需早于或等于基期(2023年9月6日):
    // 单位净值 = 基期单位净值 / (1 + 本基金日增长率)N
    // 其中，N 是选择的日期与数据基期相差的天数。
    // resultNav.value = ""
    // if (FormConten.value.statu === 2) {
    //   resultNav.value = Math.pow(FormConten.value.nav / (1 + FormConten.value.dailyGrowthRate), dayCount).toFixed(4)
    // } else {
    //   if (dayCount > 0) {
    //     resultNav.value = (Math.pow(FormConten.value.nav / (1 + FormConten.value.dailyGrowthRate), dayCount) - FormConten.value.dividend / 10).toFixed(4)
    //   } else {
    //     resultNav.value = (Math.pow(FormConten.value.nav * (1 + FormConten.value.dailyGrowthRate), dayCount) - FormConten.value.dividend / 10).toFixed(4)
    //   }
    // }

  }
  // 关闭信息弹窗 -- 清空时间
  function close_Subscribe() {
    DateValue.value = "";
    FormConten.value.share = ""
    FormConten.value.charge = ""
    FormConten.value.dealPassword = ""
    FormConten.value.subscribeMoney = ""
    DialogVisible.value = false;
  }
  // 确定申购-分红-赎回等操作
  async function sure_Subscribe(nums) {
    const {
      dealPassword,
      shouldHavePaidTax,
      bookLoses,
      actualTaxPayment,
      redemptionId,
      purchasedId
    } = FormConten.value;
    if (nums === 1) {
      const subscribeMoney = FormConten.value.subscribeMoney;
      if (!subscribeMoney || subscribeMoney === null || subscribeMoney === '') {
        ElMessage.warning("请输入申购金额");
        return;
      }
      if (!dealPassword || dealPassword === null || dealPassword === '') {
        ElMessage.warning("请输入密码");
        return;
      }
      const data = {
        "planId": route.query.planId,
        "taskId": route.query.taskId,
        purchasedTime: DateValue.value,
        PurchasedPrice: SGF.value,
        ...FormConten.value
      }
      btnloading.value = true;
      const res = await SecuritiesFundDividendPurchasedFundDividend(data);
      if (res.success) {
        ElMessage.success(res.msg);
        btnloading.value = false;
        close_Subscribe();
        GetDataLists();
      } else {
        ElMessage.error(res.msg);
        setTimeout(() => { btnloading.value = false; }, 1500)
      }
    } else if (nums === 2) {
      FormConten.value = {};
      close_Subscribe();
      GetDataLists();
    } else if (nums === 3) {
      const { purchasedId, share, charge, amount, registrationTime } = FormConten.value;
      if (!share || share === null || share === '') {
        ElMessage.warning("请输入赎回份额");
        return;
      }
      if (!charge || charge === null || charge === '') {
        ElMessage.warning("请输入赎回费用");
        return;
      }
      if (!dealPassword || dealPassword === null || dealPassword === '') {
        ElMessage.warning("请输入密码");
        return;
      }
      const data = {
        purchasedId,
        "planId": route.query.planId,
        "taskId": route.query.taskId,
        redemptionNumber: share,
        redemptionMoney: amount,
        redemptionCharges: charge,
        dealPassword: dealPassword,
        redemptionTime: DateValue.value
      };
      btnloading.value = true;
      const res = await SecuritiesFundDividendFundRedemption(data);
      if (res.success) {
        ElMessage.success(res.msg);
        GetDataLists();
        close_Subscribe();
        btnloading.value = false;
      } else {
        ElMessage.error(res.msg);
        setTimeout(() => { btnloading.value = false; }, 1500)
      }
    } else if (nums === 4) {
      const data = {
        PlanId: route.query.planId,
        TaskId: route.query.taskId,
        bookLoses: bookLoses,
        PurchasedId: purchasedId,
        RedemptionId: redemptionId,
        actualTaxPayment: actualTaxPayment,
        shouldHavePaidTax: shouldHavePaidTax,
      }
      btnloading.value = true;
      const res = await SecuritiesFundDividendTaxPlanningAnalysis(data);
      if (res.success) {
        ElMessage.success(res.msg);
        btnloading.value = false;
        close_Subscribe();
        GetDataLists();
      } else {
        ElMessage.error(res.msg);
        setTimeout(() => { btnloading.value = false; }, 1500)
      }
    }
  }
  function handleSizeChange() { GetDataList() }
  function handleCurrentChange() { GetDataList() }
  function handleSizeChanges() { GetDataLists() }
  function handleCurrentChanges() { GetDataLists() }
  async function GetDataList() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize
    };
    const res = await SecuritiesFundDividendGetAllFundDividend(data);
    if (res.success) {
      dataList.value = res.data.items;
      pagination.total = res.data.totalCount
      loading.value = false
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => {
        loading.value = false
      }, 1500)
    }
  }

  async function GetDataLists() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: paginations.currentPage,
      pageCount: paginations.pageSize
    };
    const res = await SecuritiesFundDividendGetMyFundDividend(data);
    if (res.success) {
      dataLists.value = res.data.items;
      paginations.total = res.data.totalCount;
      loadings.value = false
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => {
        loadings.value = false
      }, 1500)
    }
  }
  // 申购
  const SGF = computed(() => {
    let nums = (Number(FormConten.value.subscribeMoney) * 0.0015).toFixed(2);
    return isNaN(nums) ? null : nums
  });


  function TwoDecimal(row, key) {
    FormConten.value[key] = addZero(row)
  }

  // 赎回金额
  /*
   @ {nav} 单位净值
  @ {share} 单位净值
  */
  const SHJE = computed(() => {
    const nums = (FormConten.value.nav * FormConten.value.share).toFixed(2);
    FormConten.value.amount = nums;
    return isNaN(nums) ? null : nums;
  })

  // 赎回
  const SGFS = computed(() => {
    let nums = (FormConten.value.subscriptionAmount / FormConten.value.nav).toFixed(0);
    return isNaN(nums) ? null : nums
  })


  function myvalidator(value) {
    if (!pattern.test(value))
      FormConten.value.subscribeMoney = value.toString().replace(/(\.\d+)$/, '')

  }

  onMounted(() => {
    GetDataList()
    GetDataLists()
  })
  return {
    SGF,
    SGFS,
    SHJE,
    columns,
    loading,
    resultNav,
    dataList,
    DateValue,
    pagination,
    loadings,
    btnloading,
    dataLists,
    FormConten,
    DialogState,
    paginations,
    DateVisible,
    DialogVisible,
    Buy,
    TwoDecimal,
    myvalidator,
    close_date,
    sure_date,
    close_Subscribe,
    sure_Subscribe,
    handleSizeChange,
    handleCurrentChange,
    handleSizeChanges,
    handleCurrentChanges
  }
}
